{% extends 'layout/manage.html' %}
{% load static %}
{% block title %}{% endblock %}

{% block css %}
    <style>
        .layui-row div {
            border: 1px solid #0C1021;

        }
    </style>
{% endblock %}

{% block content %}
    <div class="layui-container">

        <div class="layui-col-md12" style="padding-top: 6%">
            <div id="chart" ondblclick="myChartDivClick()" style="width:100%;min-width:700px;min-height:500px;">
            </div>
        </div>
    </div>

    <input id="csrf_token" value="{{ csrf_token }}" hidden="hidden"/>
    <input id="ms_list" value="{{ ms_list }}" hidden="hidden"/>
    <input id="project_id" value="{{ request.web.project.id }}" hidden="hidden"/>
{% endblock %}

{% block js %}
    <script>
        const ms_list = eval(document.getElementById("ms_list").value);
        console.log('ms_list', ms_list)
        ms_list.map(ms => ms.name)
        var myChart = echarts.init(document.getElementById("chart"));
        layer.tips('双击里程碑内空白处添加新里程碑，单击里程碑spot修改里程碑。', document.getElementById("chart"), {
            tips: 1,
            time: 20000
        });
        let axisData = ms_list.map(ms => ms.name)
        let dataBase = 50
        const data = axisData.map(function (item, i) {
            return dataBase += 50;
        });
        console.log('data:{}', data)
        const links = data.map(function (item, i) {
            return {
                source: i,
                target: i + 1
            };
        });
        links.pop();
        option = {
            title: {
                text: '项目里程碑'
            },
            tooltip: {
                show: true,
                trigger: 'axis',
                {#formatter: '{b0}{c0}<br />'#}
                formatter: function (params, ticket, callback) {
                    let color = 'red'
                    return '<div style="height:120px;width:220px;text-align: center">' +
                        '<label style="color:' + `${color}` + '">' + '*' + '</label> <br>' +
                        '里程碑:' + params[0].axisValue +
                        '<br>' +
                        '周期:' + ms_list[params[0].dataIndex].date_range + '</div>'
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: axisData,
                axisLabel: {
                    fontStyle: 'normal',
                    fontWeight: 'bolder',
                    fontSize: 18,
                    formatter: function (value, index) {
                        console.log('value ', value)
                        console.log('index ', index)
                        return value + '\n' + ms_list[index].date_range
                    }
                }

            },
            yAxis: {
                type: 'value',
                show: false,
                max: 350,
                axisLabel: {
                    formatter: function () {
                        return "";
                    }
                }

            },
            dataZoom: [
                {
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'none',
                    zoomLock: true,
                    top: 0,
                    height: 20
                },
                {
                    type: 'slider',
                    yAxisIndex: 0,
                    filterMode: 'none',
                    zoomLock: true,
                    width: 20
                },
                {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'none',
                    bottom: -30
                },
                {
                    type: 'inside',
                    yAxisIndex: 0,
                    filterMode: 'none',
                    bottom: -30
                }
            ],
            series: [
                {
                    type: 'graph',
                    layout: 'none',
                    coordinateSystem: 'cartesian2d',
                    symbolSize: 40,
                    label: {
                        show: true
                    },
                    edgeSymbol: ['circle', 'arrow'],
                    edgeSymbolSize: [4, 10],
                    data: data,
                    links: links,
                    lineStyle: {
                        color: '#2f4554'
                    }
                }
            ]
        };

        myChart.showLoading()
        myChart.setOption(option);
        myChart.hideLoading()

        const formContent = '<div class="layui-form">' +
            '<input id="milestoneId" hidden="hidden">' +
            '<input type="text" required id="milestoneName" name="name" placeholder="里程碑名" class="layui-input">' +
            '<hr class="ws-space-16">' +
            '<textarea required id="milestoneRemark" name="remark" placeholder="里程碑概述" class="layui-textarea"></textarea>' +
            '</div>' +
            ' <div class="layui-form-item">' +
            ' <div class="layui-inline">' +
            '<hr class="ws-space-16">' +
            '<label class="layui-form-label">周期</label>' +
            '<div class="layui-inline" id="ID-laydate-rangeLinked">' +
            ' <div class="layui-input-inline">' +
            '<input required type="text" autocomplete="off" id="ID-laydate-start-date-1" class="layui-input" placeholder="开始日期">' +
            '</div>' +
            '<div class="layui-form-mid">-</div>' +
            '<div class="layui-input-inline">' +
            '<input required type="text" autocomplete="off" id="ID-laydate-end-date-1" class="layui-input" placeholder="结束日期">' +
            '</div>' +
            '</div>' +
            '<hr class="ws-space-16">' +
            '<input lay-checkbox type="checkbox" id="syncIssues" name="syncIssues" value="0" checked>同步里程碑tag到issues，当前已同步' +
            '<a href="javascript:void(0)" onclick="checkoutMsIssues(document.getElementById(`milestoneId`).value)"><span id="syncCount">0</span>条</a>' +
            '</div>' +
            '</div>'


        let milestoneDates = null

        myChart.on("click", function (params) {
            let dataIndex = params.dataIndex;
            {#console.log('seriesIndex',seriesIndex)#}
            console.log('dataIndex', dataIndex)
            option.tooltip.show = false
            event.stopPropagation(); // 阻止事件冒泡
            layer.msg('chart click')
            var milestoneWindow = layer.open({
                title: '请输入里程碑信息',
                content: formContent,
                success: function (layero, index) {
                    milestoneDates = ms_list[dataIndex].date_range
                    layui.use(function () {
                        var laydate = layui.laydate;
                        // 日期范围 - 左右面板联动选择模式
                        laydate.render({
                            elem: '#ID-laydate-rangeLinked',
                            range: ['#ID-laydate-start-date-1', '#ID-laydate-end-date-1'],
                            value: ms_list[dataIndex].date_range,
                            rangeLinked: true, // 开启日期范围选择时的区间联动标注模式 ---  2.8+ 新增
                            done: function (value, date) {
                                milestoneDates = value
                            }
                        });
                    })
                },
                btn: ['更新', '删除'],
                yes: function (value, index, elem) {
                    let milestoneId = $("#milestoneId").val()
                    let milestoneName = $("#milestoneName").val()
                    let milestoneRemark = $("#milestoneRemark").val()
                    let syncIssues = $("#syncIssues").is(':checked')
                    if (!milestoneId) {
                        layer.msg('破损的里程碑，请删除重加入');
                        return
                    }
                    if (!milestoneName || !milestoneRemark || !milestoneDates) {
                        layer.msg('请填写完毕内容');
                        return
                    }
                    let mlstoneRecordLoading = layer.load(0);
                    layer.confirm('确定将' + milestoneDates + '的issues纳入到里程碑:\"' + milestoneName + '\"？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        {#layer.msg('第一个回调', {icon: 1});#}
                        $.ajax({
                            url: "{% url 'milestone_add_or_update' project_id=request.web.project.id %}",
                            type: "POST",
                            data: {
                                "milestone_id": milestoneId,
                                "milestone_name": milestoneName,
                                "milestone_remark": milestoneRemark,
                                "milestone_date_range": milestoneDates,
                                "sync_issues": syncIssues,
                                "csrfmiddlewaretoken": $("#csrf_token").val()
                            },
                            dataType: "JSON",
                            success: function (res) {
                                console.log(res);
                                if (res.status) {
                                    console.log("reload")
                                    location.reload();
                                    layer.msg('操作成功')
                                } else {

                                }
                            }
                        })
                        layer.close(mlstoneRecordLoading)
                    }, function () {
                        layer.close(mlstoneRecordLoading)
                        {% comment %}   layer.msg('第二个回调', {
                               time: 20000, // 20s 后自动关闭
                               btn: ['明白了', '知道了']
                           });{% endcomment %}
                    });
                    {#layer.close(milestoneWindow)#}
                },
                btn2() {
                    let milestoneId = $("#milestoneId").val()
                    let milestoneName = $("#milestoneName").val()
                    if (!milestoneId) {
                        layer.msg('不可删除');
                        return
                    }
                    let mlstoneDelLoading = layer.load(0);
                    layer.confirm('确定将里程碑:\"' + milestoneName + '\"删除？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        {#layer.msg('第一个回调', {icon: 1});#}
                        $.ajax({
                            url: "{% url 'milestone_del' project_id=request.web.project.id %}",
                            type: "POST",
                            data: {
                                "milestone_id": milestoneId,
                                "csrfmiddlewaretoken": $("#csrf_token").val()
                            },
                            dataType: "JSON",
                            success: function (res) {
                                console.log(res);
                                if (res.status) {
                                    console.log("reload")
                                    location.reload();
                                    layer.msg('操作成功')
                                } else {

                                }
                            }
                        })
                        layer.close(mlstoneDelLoading)
                    }, function () {
                        layer.close(mlstoneDelLoading)
                    });
                    {#layer.close(milestoneWindow)#}
                },
                end: function () {
                    //更新索引
                    {% comment %}if (typeof layer.escIndex === 'object') {
                        layer.escIndex.splice(0, 1);
                    }{% endcomment %}
                }
            });
            $(document).keyup(function (event) {
                if (event.which === 27) {
                    //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算
                    layer.close(milestoneWindow);
                }
            })
            $("#milestoneId").val(ms_list[dataIndex].id)
            $("#milestoneName").val(ms_list[dataIndex].name)
            $("#milestoneRemark").val(ms_list[dataIndex].remark)
            $("#syncCount").text(ms_list[dataIndex].sync_count)
        });

        function myChartDivClick() {
            layer.msg('chart div click')
            var milestoneWindow = layer.open({
                title: '请输入里程碑信息',
                content: formContent,
                success: function (layero, index) {
                    layui.use(function () {
                        var laydate = layui.laydate;
                        // 日期范围 - 左右面板联动选择模式
                        laydate.render({
                            elem: '#ID-laydate-rangeLinked',
                            range: ['#ID-laydate-start-date-1', '#ID-laydate-end-date-1'],
                            rangeLinked: true, // 开启日期范围选择时的区间联动标注模式 ---  2.8+ 新增
                            done: function (value, date) {
                                milestoneDates = value
                            }
                        });
                    })
                },
                yes: function (value, index, elem) {
                    let milestoneId = $("#milestoneId").val()
                    let milestoneName = $("#milestoneName").val()
                    let milestoneRemark = $("#milestoneRemark").val()
                    let syncIssues = $("#syncIssues").is(':checked')
                    if (!milestoneName || !milestoneRemark || !milestoneDates) {
                        layer.msg('请填写完毕内容');
                        return
                    }
                    let mlstoneRecordLoading = layer.load(0);
                    layer.confirm('确定将' + milestoneDates + '的issues纳入到里程碑:\"' + milestoneName + '\"？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        {#layer.msg('第一个回调', {icon: 1});#}
                        $.ajax({
                            url: "{% url 'milestone_add_or_update' project_id=request.web.project.id %}",
                            type: "POST",
                            data: {
                                "milestone_id": milestoneId,
                                "milestone_name": milestoneName,
                                "milestone_remark": milestoneRemark,
                                "milestone_date_range": milestoneDates,
                                "sync_issues": syncIssues,
                                "csrfmiddlewaretoken": $("#csrf_token").val()
                            },
                            dataType: "JSON",
                            success: function (res) {
                                console.log(res);
                                if (res.status) {
                                    console.log("reload")
                                    location.reload();
                                } else {

                                }
                            }

                        })
                        layer.close(mlstoneRecordLoading)
                    }, function () {
                        layer.close(mlstoneRecordLoading)
                        {% comment %}   layer.msg('第二个回调', {
                               time: 20000, // 20s 后自动关闭
                               btn: ['明白了', '知道了']
                           });{% endcomment %}
                    });

                    {#layer.close(milestoneWindow)#}

                },
                end: function () {
                    //更新索引
                    {% comment %}if (typeof layer.escIndex === 'object') {
                        layer.escIndex.splice(0, 1);
                    }{% endcomment %}
                }
            });
            //when press esc (event27) then close prompt of editor
            $(document).keyup(function (event) {
                if (event.which === 27) {
                    //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算
                    layer.close(milestoneWindow);
                }
            })
        }

        function refreshOptionWithMilestone(milestoneData) {
            option.xAxis.data = milestoneData
            myChart.setOption(option)
            localStorage.setItem('milestoneData', milestoneData)
        }

        /**
         * 查看milestone issues
         * @param milestoneId
         */
        function checkoutMsIssues(milestoneId) {
            var url = "{% url 'issues' project_id=request.web.project.id %}?milestone_id=" + milestoneId; // 构建URL
            window.open(url)
        }




    </script>
{% endblock %}